package com.example.dormitorymanagement.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.dormitorymanagement.entity.Dormroom;
import com.example.dormitorymanagement.entity.Service;
import com.example.dormitorymanagement.entity.Student;
import com.example.dormitorymanagement.entity.simplestudent;
import com.example.dormitorymanagement.exception.AbnormalPermissions;
import com.example.dormitorymanagement.mapper.ServiceMapper;
import com.example.dormitorymanagement.service.impl.ServiceServiceImpl;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.server.session.InMemoryWebSessionStore;


import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author admin
 * @since 2021-06-04
 */
@Api(tags = "宿舍维修，权限低：维修的上报，维修的修改，维修的状态改变，权限高：维修所有操作")
@RestController
//@CrossOrigin
@RequestMapping("/service")
public class ServiceController {

    @Autowired
    private ServiceServiceImpl serviceimpl;

    @Autowired
    private ServiceMapper serviceMapper;

    @Autowired
    private com.example.dormitorymanagement.service.impl.suthorityservice suthorityservice;


    @PostMapping(value = "/addormodify")
    @ApiOperation(value = "对维修进行添加或者修改")
    public Map<String,Object> addormodify(@RequestBody Service service, HttpServletRequest request) throws AbnormalPermissions {
       Map<String, Object> map = suthorityservice.verification(request);

        if (map.size() != 0)
        {
            return map;
        }

        QueryWrapper<Service> serviceQueryWrapper = new QueryWrapper<>();

        if (service.getId() != null && service.getId() != 0)
        {
            //在修改之前，先进行判断，在数据库中是否存在该宿舍编号，防止出现修改后出现一个宿舍，有两条上报的数据都是0的现象

            serviceQueryWrapper.eq("id",service.getId());

            if (serviceMapper.selectOne(serviceQueryWrapper).getStatus() == 1)
            {
                map.put("stat",false);

                map.put("message","修改失败，原因：该数据的状态已为1");

                return map;
            }

            serviceQueryWrapper.eq("building",service.getBuilding()).eq("number",service.getNumber());

            List<Service> services = serviceMapper.selectList(serviceQueryWrapper);

            if (services.size() != 0)
            {
                for (Service service1 : services) {

                    if (service1.getStatus() == 0)
                    {
                        map.put("stat",false);
                        map.put("message","修改失败，原因：要修改的宿舍存在该宿舍还没解决维修的问题");

                        return map;
                    }

                }
            }

            UpdateWrapper<Service> serviceUpdateWrapper = new UpdateWrapper<>();

            serviceUpdateWrapper
                    .set("building",service.getBuilding())
                    .set("number",service.getNumber())
                    .set("report",service.getReport())
                    .set("phone",service.getPhone())
                    .set("reason",service.getReason())
                    .eq("id",service.getId());

            int delete = serviceMapper.update(null,serviceUpdateWrapper);

            if ( delete == 1 )
            {
                map.put("stat",false);
                map.put("message","修改成功");

                return map;
            }

            map.put("stat",true);

            map.put("message","修改失败");

            return map;

        }

        service.setReportingtime(LocalDateTime.now());

        service.setResolutiontime(LocalDateTime.now());

        service.setStatus(0);

        //先查询数据库中，是否存在该宿舍的报修，如果存在就看这条数据是否已经解决，如果上报的维修还没解决，就不让新添加

        serviceQueryWrapper.eq("building",service.getBuilding()).eq("number",service.getNumber());

        List<Service> services = serviceMapper.selectList(serviceQueryWrapper);

        if (services.size() != 0)
        {
            for (Service service1 : services) {

                if (service1.getStatus() == 0)
                {
                    map.put("stat",false);
                    map.put("message","维修上报失败，原因：存在该宿舍还没解决维修");

                    return map;
                }

            }
        }

        boolean save = serviceimpl.save(service);

        if (save)
        {
            map.put("stat",true);

            map.put("message","维修上报成功");

            return map;

        }

        map.put("stat",false);

        map.put("message","维修上报失败");

        return map;

    }

    @GetMapping(value = "/changestate")
    @ApiOperation(value = "改变状态，通过id，将该数据的状态由0改为1，状态为1的数据，将不能进行修改")
    public Map<String,Object> changestate(@ApiParam(name = "id",value = "通过id，来改变该数据的状态",required = true) @RequestParam(value = "id") Integer id)
    {

        Map<String,Object> map = new HashMap<>();

        //先看要修改的数据的状态是否为1，如果是1的话，就不进行修改了，
        QueryWrapper<Service> serviceQueryWrapper = new QueryWrapper<>();

        serviceQueryWrapper.eq("id",id);

        Service service = serviceMapper.selectOne(serviceQueryWrapper);

        if (service.getStatus() == 1)
        {
            map.put("stat",false);

            map.put("message","该数据的状态已为1，修改失败");

            return map;
        }

        UpdateWrapper<Service> serviceUpdateWrapper = new UpdateWrapper<>();

        serviceUpdateWrapper.set("status",1).set("resolutiontime",LocalDateTime.now()).eq("id",id);

        int update = serviceMapper.update(null, serviceUpdateWrapper);

        if (update == 1)
        {
            map.put("stat",true);

            map.put("message","修改成功");

            return map;
        }

        map.put("stat",false);

        map.put("message","修改失败");

        return map;

    }

    @GetMapping(value = "/deleteservice")
    @ApiOperation(value = "通过id来删除对应班级管理")
    public Map<String,Object> deleteservice(@ApiParam(name = "id",value = "通过id删除对应的数据",required = true) @RequestParam(value = "id") Integer id,HttpServletRequest request) throws AbnormalPermissions {
        Map<String, Object> map = suthorityservice.verification(request);

        if (map.size() != 0)
        {
            return map;
        }
        UpdateWrapper<Service> serviceUpdateWrapper = new UpdateWrapper<>();

        serviceUpdateWrapper.eq("id",id);

        int delete = serviceMapper.delete(serviceUpdateWrapper);

        if (delete == 1)
        {
            map.put("stat",true);

            map.put("message","删除成功");

            return map;
        }

        map.put("stat",false);

        map.put("message","删除失败");

        return map;

    }

    @GetMapping(value = "/getservice")
    @ApiOperation(value = "通过条件来获取维修表中的所有数据，一页10条数据")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "building",value = "第几栋宿舍，不传值则默认获取所有楼栋的数据",dataType = "int",required = false),
            @ApiImplicitParam(name = "pc",value = "第几页，不传值默认为第一页",dataType = "int"),
            @ApiImplicitParam(name = "status",value = "状态，这个值不传代表查找状态是0和1的，0代表查找未解决的，1代表查找已解决的",dataType = "int",required = false),
    })
    public Map<String, Object> dormroom(Integer building, Integer pc,Integer status)
    {

        Map<String,Object> map = new HashMap<>();

        if (pc == null)
        {
            pc = 1;
        }

        QueryWrapper<Service> serviceQueryWrapper = new QueryWrapper<>();


        map.put("building",building);
        map.put("status",status);

        serviceQueryWrapper.allEq(map,false).orderByAsc("number");

        map.clear();

        Page<Service> servicePage = new Page<>(pc,10);

        serviceMapper.selectPage(servicePage,serviceQueryWrapper);

        if ( pc > servicePage.getPages())
        {
            map.put("stat",false);

            map.put("message","页数越界，总页数：" + servicePage.getPages() + "，当前页数:" + servicePage.getCurrent());

            return map;
        }

        List<Service> services = servicePage.getRecords();

        map.put("stat",true);
        map.put("services", services);
        map.put("pages",servicePage.getPages());
        map.put("page",servicePage.getCurrent());
        map.put("total", servicePage.getTotal());
        map.put("current", servicePage.getCurrent());
        map.put("hasPrevious",servicePage.hasPrevious());
        map.put("hasNext",servicePage.hasNext());
        map.put("ypf","1");
        return map;

    }

    @GetMapping(value = "/getbuilding")
    @ApiOperation(value = "获取宿舍的楼号")
    public Map<String,Object> getbuilding()
    {
        QueryWrapper<Service> serviceQueryWrapper = new QueryWrapper<>();

        serviceQueryWrapper.groupBy("building");

        List<Service> services = serviceMapper.selectList(serviceQueryWrapper);

        List<Integer> buildings = new ArrayList<>();

        services.forEach(service -> {

            buildings.add(service.getBuilding());

        });

        Map<String,Object> map = new HashMap<>();

        map.put("stat",true);
        map.put("bulidings",buildings);

        return map;

    }

}




















